Telegram Group & Telegram Channel
Inverts a dictionary with non-unique hashable values.

👉Create a collections.defaultdict with list as the default value for each key.

👉Use dictionary.items() in combination with a loop to map the values of the dictionary to keys using dict.append().

👉Use dict() to convert the collections.defaultdict to a regular dictionary.

CODE:

from collections import defaultdict

def collect_dictionary(obj):
inv_obj = defaultdict(list)
for key, value in obj.items():
inv_obj[value].append(key)
return dict(inv_obj)

Example:

ages = {
'Peter': 10,
'Isabel': 10,
'Anna': 9,
}
collect_dictionary(ages)

Output: { 10: ['Peter', 'Isabel'], 9: ['Anna'] }

Share and Support
@Python_Codes



tg-me.com/python_codes/220
Create:
Last Update:

Inverts a dictionary with non-unique hashable values.

👉Create a collections.defaultdict with list as the default value for each key.

👉Use dictionary.items() in combination with a loop to map the values of the dictionary to keys using dict.append().

👉Use dict() to convert the collections.defaultdict to a regular dictionary.

CODE:

from collections import defaultdict

def collect_dictionary(obj):
inv_obj = defaultdict(list)
for key, value in obj.items():
inv_obj[value].append(key)
return dict(inv_obj)

Example:

ages = {
'Peter': 10,
'Isabel': 10,
'Anna': 9,
}
collect_dictionary(ages)

Output: { 10: ['Peter', 'Isabel'], 9: ['Anna'] }

Share and Support
@Python_Codes

BY Python Codes


Warning: Undefined variable $i in /var/www/tg-me/post.php on line 283

Share with your friend now:
tg-me.com/python_codes/220

View MORE
Open in Telegram


Python Codes Telegram | DID YOU KNOW?

Date: |

At a time when the Indian stock market is peaking and has rallied immensely compared to global markets, there are companies that have not performed in the last 10 years. These are definitely a minor portion of the market considering there are hundreds of stocks that have turned multibagger since 2020. What went wrong with these stocks? Reasons vary from corporate governance, sectoral weakness, company specific and so on. But the more important question is, are these stocks worth buying?

If riding a bucking bronco is your idea of fun, you’re going to love what the stock market has in store. Consider this past week’s ride a preview.The week’s action didn’t look like much, if you didn’t know better. The Dow Jones Industrial Average rose 213.12 points or 0.6%, while the S&P 500 advanced 0.5%, and the Nasdaq Composite ended little changed.

Python Codes from no


Telegram Python Codes
FROM USA